package com.handpay.zztong.hp.swiper.ic;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map.Entry;

import com.handpay.framework.upcard.sdom.DomLite;
import com.handpay.framework.upcard.sdom.TagNode;

/**
 * 
 * @author <a href="mailto:justin.hou@handpay.com.cn">Sora</a>
 * @version 1.0
 * 
 * 閾惰仈閲戣瀺浜ゆ槗缁撴灉瑙ｆ瀽绫?
 */
public class UPCardsTransactionResult
{
	private final HashMap<String,String> hash_elements = new HashMap<String,String>();
		
	/**
	 * 瑙ｆ瀽閾惰仈杩斿洖缁撴灉
	 * @param respBuffer 閾惰仈鍝嶅簲鏁版嵁
	 * @return
	 */
	public boolean receive(byte[] respBuffer) 
	{
		hash_elements.clear();
		DomLite dom = new DomLite();
		TagNode root = dom.load(respBuffer, "UTF-8");
		
		if (root == null)
		{
			return false;
		}
		
		build(root, "");
		
		return true;
	}
	
	private String build(TagNode node, String path)
	{
		if (node == null)
		{
			return "";
		}

		String newPath = buildTag(node, path);
		
		for(TagNode child = node.getChild(0); child != null; child = child.getSibling())
		{
			build(child, newPath);
		}
		
		return newPath;
	}
	
	private String buildTag(TagNode node, String curPath)
	{		
		if (node.getTagType() == TagNode.TAG_TEXT)
		{
			//Caojun 澶氭潯璁板綍鐢ㄥ垎闅旂鍒嗗壊
			String key = curPath;
			String v = node.getName();
			String oldv = hash_elements.get(key);
			if(oldv != null)
			{
				//鏈夊鏉¤褰?
				String newv = oldv + CUPMobileXML.SEPARTOR + v;
				hash_elements.put(key, newv);
			}
			else
			{
				hash_elements.put(key, v);
			}
			return curPath;
		}
		
		if(curPath.length()<=0)
		{
			curPath = node.getName();
		}
		else
		{
			curPath = curPath + "." + node.getName();
		}
		
		Hashtable<String,String> attrs = node.getAttributes();
		if (attrs != null)
		{//attributes
			Iterator<Entry<String, String>> iter = node.getAttributes().entrySet().iterator();
			while (iter.hasNext())
			{
				Entry<String, String> entry = iter.next();
				String k = entry.getKey();
				String v = entry.getValue();
				
				String key = curPath + ":" + k;
				//Caojun 澶氭潯璁板綍鐢ㄥ垎闅旂鍒嗗壊
				String oldv = hash_elements.get(key.toLowerCase());
				if(oldv != null)
				{
					//鏈夊鏉¤褰?
					String newv = oldv + CUPMobileXML.SEPARTOR + v;
					hash_elements.put(key, newv);
				}
				else
				{
					hash_elements.put(key, v);
				}
			}
		}
		
		return curPath;
	}
	
	public String getElementValue(int key)
	{
		String strKey = CUPMobile.getElement(key);
		
		return hash_elements.get(strKey);
	}
}
